#ifndef TRANSFORM_TASK_H
#define TRANSFORM_TASK_H
#include "task_metadata.h"
#include <variant>
#include <memory>
#include <vector>
#include <iostream>

using namespace abc;

namespace task
{

    struct ImportsContext
    {
        std::vector<std::shared_ptr<ImportDescriptor>> imports;
    };

    class TransformTask
    {
    public:
        virtual ~TransformTask() = default;

        explicit TransformTask(std::shared_ptr<TaskParam> param,
                               AbckitCoreFunction *func,
                               AbckitGraph *graph,
                               std::vector<std::shared_ptr<ImportDescriptor>> &importDecs)
            : param_(std::move(param)), func_(func), graph_(graph), importDecs_(importDecs) {};

        TransformTask(const TransformTask &) = delete;
        TransformTask &operator=(const TransformTask &) = delete;

        std::shared_ptr<TaskParam> getParam() const
        {
            return param_;
        }

        virtual bool analyze(InstStructType structType)
        {
            std::cout << "父类Task inst分析结果: 未命中" << std::endl;
            return false;
        };

        void execute(InstStructType instStruct)
        {
            bool isTarget = analyze(instStruct);
            if (!isTarget)
            {
                return;
            }
            transform(instStruct);
        };

        virtual void transform(InstStructType instStruct) = 0;

    protected:
        std::shared_ptr<TaskParam> param_;
        AbckitCoreFunction *func_;
        AbckitGraph *graph_;
        bool loadImports_ = false;
        std::vector<std::shared_ptr<ImportDescriptor>> importDecs_;

        bool containsImport(const std::string &targetName) const
        {
            return std::find_if(importDecs_.begin(), importDecs_.end(),
                                [&targetName](const std::shared_ptr<ImportDescriptor> &desc)
                                {
                                    return desc->importName == targetName;
                                }) != importDecs_.end();
        }

        std::shared_ptr<ImportDescriptor> getImportDesc(const std::string &targetName)
        {
            try
            {
                auto it = std::find_if(importDecs_.begin(), importDecs_.end(),
                                       [&](const auto &desc)
                                       {
                                           if (!desc)
                                               throw std::runtime_error("发现空指针");
                                           return desc->importName == targetName;
                                       });
                return (it != importDecs_.end()) ? *it : nullptr;
            }
            catch (const std::exception &e)
            {
                std::cerr << "查找出错: " << e.what() << std::endl;
                return nullptr;
            }
        }
    };

}

#endif